import { computed } from 'vue'

export default function useQuarterRanges(startYear = 2023, startQuarter = 1) {
    /**
 * 获取季度范围集合
 * @param {number} startYear - 起始年份
 * @param {number} startQuarter - 起始季度 (1-4)
 * @param {Date} [endDate] - 截止日期（默认当前日期）
 * @returns {Array<{label: string, start: string, end: string, value: string}>}
 */
    function getQuarterRanges(startYear = 2023, startQuarter = 1, endDate = new Date()) {
        const quarters = []
        let currentYear = startYear
        let currentQuarter = startQuarter
        const endYear = endDate.getFullYear()
        const endQuarter = Math.ceil((endDate.getMonth() + 1) / 3) // 计算当前季度

        // 季度名称映射
        const quarterNames = ['第一季度', '第二季度', '第三季度', '第四季度']

        while (
            currentYear < endYear
            || (currentYear === endYear && currentQuarter <= endQuarter)
        ) {
            const quarterStartMonth = (currentQuarter - 1) * 3 // 月份从0开始
            const quarterEndMonth = quarterStartMonth + 3

            const startDate = new Date(currentYear, quarterStartMonth, 1)
            const endDate = new Date(currentYear, quarterEndMonth, 0) // 下个月的第0天是本月最后一天

            quarters.push({
                label: `${currentYear}年${quarterNames[currentQuarter - 1]}`,
                start: formatDate(startDate),
                end: formatDate(endDate),
                value: `${currentYear}Q${currentQuarter}`, // 唯一标识符
            })

            // 跳到下一个季度
            currentQuarter++
            if (currentQuarter > 4) {
                currentQuarter = 1
                currentYear++
            }
        }

        const quarterRangs = quarters
        return quarterRangs.slice(0, quarterRangs.length - 1).reverse()
    }

    // 格式化日期为 YYYY-MM-DD
    function formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
    }

    const quarterRanges = computed(() =>
        getQuarterRanges(startYear, startQuarter),
    )

    // 获取当前季度
    const currentQuarter = computed(() => {
        const now = new Date()
        const q = Math.ceil((now.getMonth() + 1) / 3)
        return {
            label: `${now.getFullYear()}年${['第一季度', '第二季度', '第三季度', '第四季度'][q - 1]}`,
            value: `${now.getFullYear()}-Q${q}`,
        }
    })

    return { quarterRanges, currentQuarter }
}
